<template>
  <div>
    <FormPanel ref="formPanel" :list="formList" :cols="3" :collapse="false" :labelWidth="90" :isSubmitBtn="false" @formChange="formchangeFuns"></FormPanel>

    <FilterTable
      ref="table"
      :columns="butcolumns"
      :isSubmitBtn="false"
      :onColumnsChange="butcolumns => (this.butcolumns = butcolumns)"
      selectionType="single"
      columnsRef="partPartOutboundPartSalesSalesOrderChange"
    ></FilterTable>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDialog">关 闭</el-button>
      <el-button type="primary" @click="saveDialog">保 存</el-button>
    </div>
  </div>
</template>
<script>
import { isAuthorized } from '@/utils/index';
import { getStroageList } from '@/api/part/partOutbound/partBreak';
import { dictionary } from '@/utils/dictMixin';
import Cookies from 'js-cookie';
// import { StockItem } from '@/api/part/partOut/partSales/index';

const jglx_dict = [
  { text: '终端建议零售VIP价格', value: 82481001, filedName: 'NOT_TAX_INSTRUCT_PRICE' },
  { text: ' 常规订货价 ', value: 82481002, filedName: 'PLAN_PRICE' },
  { text: '含税成本价', value: 82481003, filedName: 'COST_PRICE' },
  { text: '终端建议零售价格', value: 82481004, filedName: 'INSURANCE_PRICE' },
  { text: '索赔价', value: 82481005, filedName: 'CLAIM_PRICE' },
  { text: '最新进货价', value: 82481006, filedName: 'LATEST_PRICE' }
];
export default {
  name: 'salesOrderChange',
  mixins: [dictionary],
  props: {
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    this.BaseTable = null;
    return {
      formList: this.createTopFilterList(),
      listPrice: 0, // 价格
      InitSalePrace: 0, // 初始销售价格
      listType: [],
      flagS: '', // 表单提交控制校验的状态
      butcolumns: this.createTablelistBut(),
      fromSubmitdata: {},
      storageItemsList: [] // 仓库
    };
  },
  computed: {
    priceLimit() {
      return this.InitSalePrace;
    }
  },
  watch: {
    // priceLimit(newVal, oldVal) {
    //   if (newVal) {
    //     this.formList.find(item => item.fieldName == 'PART_SALES_PRICE').min = Number(newVal) || 0;
    //   }
    // }
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.init();
    this.searchstore();
  },
  methods: {
    async init() {
      // 更新接口需要的记录 ID
      this.formList.forEach(x => {
        this.InitSalePrace = this.rowData.SALES_PRICE;
        this.listPrice = this.rowData.PART_SALES_PRICE;
        x.initialValue = this.rowData[x.fieldName];
      });
      this.listType = this.rowData;
      this.BaseTable.EXECUTE_INSERT(this.rowData);
    },
    createTopFilterList() {
      return [
        {
          type: 'SELECT',
          label: '仓库名称',
          fieldName: 'STORAGE_CODE',
          itemList: [],
          disabled: true
        },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'PART_NO',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'PART_NAME',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '价格类型',
          fieldName: 'PRICE_TYPE',
          hidden: true,
          placeholder: '',
          // initialValue: 82481001, // 终端建议零售VIP价格
          itemList: this.createDictList('8248'),
          rules: [{ type: 'number', required: true, message: '请选择价格类型', trigger: ['blur', 'change'] }],
          change: val => {
            this.price_type_change(val);
          }
        },
        {
          type: 'INPUT_NUMBER',
          label: '价格系数',
          fieldName: 'PRICE_RATE',
          rules: [{ required: true, message: '请输入价格系数', trigger: 'blur' }],
          precision: 2,
          min: 0,
          max: 9.99,
          // hidden: !isAuthorized('1313', '13131009'),
          change: val => {
            this.changecoefficient(val);
          }
        },
        {
          type: 'INPUT_NUMBER',
          label: '配件销售单价',
          fieldName: 'PART_SALES_PRICE',
          precision: 2,
          min: 0,
          disabled: true,
          // disabled: !isAuthorized('1313', '13131004'),
          change: val => {
            // this.changeMoney(val);
          }
        },
        {
          type: 'INPUT_NUMBER',
          label: '发料数量',
          fieldName: 'PART_QUANTITY',
          precision: 2,
          min: 0.01,
          change: val => {
            if (!isAuthorized('1313', '13131003')) {
              min: 0;
            }
            this.changemNum(val);
          }
        },
        {
          type: 'INPUT',
          label: '配件销售金额',
          fieldName: 'SALES_AMOUNT',
          disabled: true
        }
        // {
        //   type: 'SELECT',
        //   label: '销售方式',
        //   fieldName: 'SALES_TYPE',
        //   initialValue: 80961001,
        //   itemList: this.createDictList('8096')
        // }
        // {
        //   type: 'INPUT',
        //   label: '税额',
        //   initialValue: '0.00',
        //   fieldName: 'TAX_AMOUNT',
        //   hidden: true,
        //   disabled: true
        // }
      ];
    },
    createTablelistBut() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          initialValue: '1',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '终端建议零售VIP价格',
          sorter: true,
          dataIndex: 'NOT_TAX_INSTRUCT_PRICE',
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '常规订货价',
          sorter: true,
          dataIndex: 'PLAN_PRICE',
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '含税成本价',
          sorter: true,
          dataIndex: 'COST_PRICE',
          precision: 2,
          filter: true,
          filterType: 'number'
        },

        {
          title: '索赔价',
          sorter: true,
          dataIndex: 'CLAIM_PRICE',
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '终端建议零售价格',
          sorter: true,
          dataIndex: 'INSURANCE_PRICE',
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '最新进货价',
          sorter: true,
          dataIndex: 'LATEST_PRICE',
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '账面库存',
          dataIndex: 'STOCK_QUANTITY',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '可用库存',
          dataIndex: 'USEABLE_STOCK',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '锁定量',
          dataIndex: 'LOCKED_QUANTITY',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '替代配件',
          dataIndex: 'OPTION_NO',
          sorter: true,
          showOverflowTooltip: true,
          filter: true,
          filterType: 'input'
        },
        // {
        //   title: '替代件库存',
        //   dataIndex: 'OPTION_STOCK',
        //   sorter: true,
        //   precision: 2,
        //   filter: true,
        //   filterType: 'number'
        // },
        {
          title: '配件类别',
          dataIndex: 'PART_GROUP_CODE',
          sorter: true,
          showOverflowTooltip: true,
          editable: false,
          editType: 'select',
          editItems: this.createDictList(8247),
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList(8247)
        },
        {
          title: '单位',
          dataIndex: 'UNIT_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
        // {
        //   title: '单位CODE',
        //   dataIndex: 'UNIT_CODE',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   hidden: true
        // }
        // {
        //   title: '成本价',
        //   dataIndex: 'COST_PRICE',
        //   hidden: true,
        //   precision: 2,
        //   filter: true,
        //   filterType: 'number'
        // },
        // {
        //   title: '网点价',
        //   dataIndex: 'NODE_PRICE',
        //   hidden: true,
        //   precision: 2,
        //   filter: true,
        //   filterType: 'number'
        // },
        // {
        //   title: '配件收费金额',
        //   dataIndex: 'PART_SALES_AMOUNT',
        //   hidden: true,
        //   precision: 2,
        //   filter: true,
        //   filterType: 'number'
        // }
      ];
    },
    // 表单提交
    formchangeFuns(val) {
      this.fromSubmitdata = val;
      this.flagS = true;
    },
    async searchstore() {
      const res = await getStroageList();
      this.storageItemsList = res.data.map(x => ({ value: x.STORAGE_CODE, text: x.STORAGE_NAME, tag: x.OEM_TAG }));
      this.formList.find(x => x.fieldName == 'STORAGE_CODE').itemList = this.storageItemsList;
    },
    // 保留两位小数
    numFilter(value) {
      let realVal = parseFloat(value).toFixed(2);
      return realVal;
    },
    // 改变价格类型,每次改变价格类型时候都会对typePrice 和 listPrice 重新赋值用于计算
    price_type_change(val) {
      console.log(val);
      const filedName = jglx_dict.find(x => x.value == val).filedName;
      const PRICE_TYPE = this.listType[filedName] || 0; // 默认是1
      this.formList.find(item => item.fieldName === 'PART_SALES_PRICE').initialValue = PRICE_TYPE;
      this.listPrice = PRICE_TYPE * this.formList.find(item => item.fieldName === 'PRICE_RATE').initialValue;
      this.changeMoney(this.listPrice);
    },

    changeMoney(val) {
      // let scalePrice = Number(this.InitSalePrace).toFixed(2);
      // if (scalePrice > Number(val).toFixed(2)) {
      //   val = scalePrice;
      // }

      this.formList.find(item => item.fieldName === 'PART_SALES_PRICE').initialValue = this.numFilter(val);
      // if (this.listPrice != 0) {
      //   this.formList.find(item => item.fieldName === 'PRICE_RATE').initialValue = this.numFilter(val / this.listPrice); // 金额改变时候改变参数
      // }
      const num = this.formList.find(item => item.fieldName === 'PART_QUANTITY').initialValue;
      this.formList.find(item => item.fieldName === 'SALES_AMOUNT').initialValue = this.numFilter(val * num);
    },
    // 改变系数参数
    changecoefficient(val) {
      const num = this.formList.find(item => item.fieldName === 'PART_QUANTITY').initialValue;
      let money = this.numFilter(this.listPrice * val); // 参数改变时候，改变金额
      this.formList.find(item => item.fieldName === 'PART_SALES_PRICE').initialValue = money;
      this.formList.find(item => item.fieldName === 'SALES_AMOUNT').initialValue = this.numFilter(money * num);
    },
    // 改变数量
    changemNum(val) {
      let reg = /^(-)?(?!0\d|[0.]+$)\d+(\.\d{1,2})?$/;
      let res = String(val).split('.');
      let num = 0;
      if (res[1] != undefined) {
        num = res[1].length;
      }
      if (!reg.test(val) || num > 2) {
        return this.$notify.warning({ title: '提示信息', message: '请输入正确的数值,保留2位小数' });
      } else {
        const money = this.formList.find(item => item.fieldName === 'PART_SALES_PRICE').initialValue;
        this.formList.find(item => item.fieldName === 'SALES_AMOUNT').initialValue = this.numFilter(val * money);
      }
    },

    // 选中确定后关闭窗口
    saveDialog() {
      this.flagS = false;
      let json = this.rowData;
      const nums = this.formList.find(item => item.fieldName === 'PART_QUANTITY').initialValue;
      this.$refs.formPanel.SUBMIT_FORM();
      let formdata = Object.assign({}, json, this.fromSubmitdata);
      let reg = /^(-)?(?!0\d|[0.]+$)\d+(\.\d{1,2})?$/;
      let res = String(nums).split('.');
      let num = 0;
      if (res[1] != undefined) {
        num = res[1].length;
      }
      if (!reg.test(nums) || num > 2) {
        return this.$notify.warning({ title: '提示信息', message: '请输入非0的数值,保留2位小数' });
      }
      if (this.flagS == true) {
        formdata.PRICE_TYPE = this.formList.find(x => x.fieldName == 'PRICE_TYPE').initialValue;
        if (formdata.PART_SALES_PRICE < formdata.COST_PRICE) {
          this.$confirm('该配件销售价格低于成本价格，是否继续添加配件？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$emit('saveDialog', formdata);
          });
        } else {
          this.$emit('saveDialog', formdata);
        }
      } else {
        return this.$notify.warning({ title: '提示信息', message: '请完成相关校验' });
      }
    },
    // 点击取消关闭窗口
    closeDialog() {
      this.$emit('close', false);
    }
  }
};
</script>
<style lang="less" scoped>
.confirm-button-style {
  margin-top: 10px;
  text-align: center;
}
</style>
